<template>
  <div class="prescription-detail">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-button @click="handleBack" type="primary" plain>
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <h2 class="page-title">
        订单详情 - {{ getOrderStatusText(orderDetail.orderStatus) }}
      </h2>
    </div>

    <!-- 订单基本信息 -->
    <el-card class="info-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>订单基本信息</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <label>订单编号：</label>
            <span>{{ orderDetail.orderNo }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>处方编号：</label>
            <span>{{ orderDetail.prescriptionInfo?.prescriptionNo }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>创建时间：</label>
            <span>{{ formatDateTime(orderDetail.createTime) }}</span>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <label>订单状态：</label>
            <el-tag :type="getOrderStatusType(orderDetail.orderStatus)">
              {{ getOrderStatusText(orderDetail.orderStatus) }}
            </el-tag>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>处方状态：</label>
            <el-tag
              :type="
                getPrescriptionStatusType(
                  orderDetail.prescriptionInfo?.prescriptionStatus
                )
              "
            >
              {{
                getPrescriptionStatusText(
                  orderDetail.prescriptionInfo?.prescriptionStatus
                )
              }}
            </el-tag>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>订单金额：</label>
            <span class="amount">¥{{ orderDetail.cost?.toFixed(2) }}</span>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <label>优惠券：</label>
            <span class="coupon"
              >-¥{{ orderDetail.couponAmount?.toFixed(2) }}</span
            >
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>实际支付：</label>
            <span class="actual-payment"
              >¥{{ orderDetail.actualPayment?.toFixed(2) }}</span
            >
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>支付方式：</label>
            <span>{{ orderDetail.paymentMethod || "未支付" }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 患者信息 -->
    <el-card class="info-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>患者信息</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <label>患者姓名：</label>
            <span>{{ orderDetail.patientInfo?.patientName }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>性别：</label>
            <span>{{ orderDetail.patientInfo?.sex }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>年龄：</label>
            <span>{{ orderDetail.patientInfo?.age }}岁</span>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <label>手机号：</label>
            <span>{{ orderDetail.patientInfo?.phone }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>所患疾病：</label>
            <span>{{ orderDetail.patientInfo?.disease }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>过敏史：</label>
            <span>{{ orderDetail.patientInfo?.allergyHistory || "无" }}</span>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <label>肝功能：</label>
            <span>{{ orderDetail.patientInfo?.liverFunction }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>肾功能：</label>
            <span>{{ orderDetail.patientInfo?.kidneyFunction }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>生育状态：</label>
            <span>{{ orderDetail.patientInfo?.reproductiveStatus }}</span>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="info-item">
            <label>病情描述：</label>
            <span>{{ orderDetail.patientInfo?.diseaseDescription }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 处方信息 -->
    <el-card class="info-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>处方信息</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <label>处方编号：</label>
            <span>{{ orderDetail.prescriptionInfo?.prescriptionNo }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>开单时间：</label>
            <span>{{
              formatDateTime(orderDetail.prescriptionInfo?.createTime)
            }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>处方状态：</label>
            <el-tag
              :type="
                getPrescriptionStatusType(
                  orderDetail.prescriptionInfo?.prescriptionStatus
                )
              "
            >
              {{
                getPrescriptionStatusText(
                  orderDetail.prescriptionInfo?.prescriptionStatus
                )
              }}
            </el-tag>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <label>医生：</label>
            <span>{{ orderDetail.prescriptionInfo?.doctor }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>科室：</label>
            <span>{{ orderDetail.prescriptionInfo?.departmentName }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <label>发药状态：</label>
            <el-tag
              :type="
                getDispensingStatusType(
                  orderDetail.prescriptionInfo?.dispensingStatus
                )
              "
            >
              {{
                getDispensingStatusText(
                  orderDetail.prescriptionInfo?.dispensingStatus
                )
              }}
            </el-tag>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="info-item">
            <label>初步诊断：</label>
            <span>{{ orderDetail.prescriptionInfo?.primaryDiagnosis }}</span>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="info-item">
            <label>处理意见：</label>
            <span>{{ orderDetail.prescriptionInfo?.advice }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 药品清单 -->
    <el-card class="info-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>药品清单</span>
        </div>
      </template>
      <el-table :data="orderDetail.prescriptionInfo?.drugs || []" border stripe>
        <el-table-column prop="drugName" label="药品名称" min-width="150" />
        <el-table-column prop="specification" label="规格" min-width="120" />
        <el-table-column prop="dosage" label="用法用量" min-width="150" />
        <el-table-column
          prop="quantity"
          label="数量"
          width="80"
          align="center"
        />
        <el-table-column
          prop="unitPrice"
          label="单价"
          width="100"
          align="right"
        >
          <template #default="scope">
            ¥{{ scope.row.unitPrice?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="subTotal" label="小计" width="100" align="right">
          <template #default="scope">
            ¥{{ scope.row.subTotal?.toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ArrowLeft } from "@element-plus/icons-vue";
import { OrderAPI } from "../api/order";

// 路由相关
const route = useRoute();
const router = useRouter();
const orderId = route.params.id as string;

// 订单详情数据
const orderDetail = ref({
  id: 0,
  orderNo: "",
  orderStatus: 0,
  orderStatusName: "",
  purchaseMethod: 0,
  purchaseMethodName: "",
  cost: 0,
  couponAmount: 0,
  actualPayment: 0,
  paymentMethod: "",
  paymentTime: "",
  createTime: "",
  patientInfo: {
    patientName: "",
    sex: "",
    age: 0,
    phone: "",
    address: "",
    disease: "",
    liverFunction: "",
    kidneyFunction: "",
    allergyHistory: "",
    reproductiveStatus: "",
    diseaseDescription: "",
  },
  prescriptionInfo: {
    prescriptionNo: "",
    createTime: "",
    prescriptionStatus: 0,
    prescriptionStatusName: "",
    dispensingStatus: 0,
    dispensingStatusName: "",
    doctor: "",
    department: 0,
    departmentName: "",
    primaryDiagnosis: "",
    advice: "",
    drugs: [],
  },
});

// 订单状态枚举
const OrderStatus = {
  PENDING: 0, // 待支付
  COMPLETED: 5, // 已完成
  INVALID: 10, // 已失效
};

// 处方状态枚举
const PrescriptionStatus = {
  PENDING: 0, // 待审核
  APPROVED: 5, // 已审核
  COMPLETED: 10, // 已完成
  INVALID: 15, // 已失效
};

// 购药方式枚举
const PurchaseMethod = {
  PHARMACY: 0, // 药店购药
  ONLINE: 1, // 线上购药
};

// 发药状态枚举
const DispensingStatus = {
  PENDING: 0, // 待支付
  PROCESSING: 1, // 发药中
  COMPLETED: 2, // 已发药
  CANCELLED: 3, // 已取消
};

// 获取订单状态类型
const getOrderStatusType = (status: number) => {
  const statusMap: Record<number, string> = {
    [OrderStatus.PENDING]: "warning",
    [OrderStatus.COMPLETED]: "success",
    [OrderStatus.INVALID]: "info",
  };
  return statusMap[status] || "info";
};

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    [OrderStatus.PENDING]: "待支付",
    [OrderStatus.COMPLETED]: "已完成",
    [OrderStatus.INVALID]: "已失效",
  };
  return statusMap[status] || "未知";
};

// 获取处方状态类型
const getPrescriptionStatusType = (status: number) => {
  const statusMap: Record<number, string> = {
    [PrescriptionStatus.PENDING]: "warning",
    [PrescriptionStatus.APPROVED]: "primary",
    [PrescriptionStatus.COMPLETED]: "success",
    [PrescriptionStatus.INVALID]: "info",
  };
  return statusMap[status] || "info";
};

// 获取处方状态文本
const getPrescriptionStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    [PrescriptionStatus.PENDING]: "待审核",
    [PrescriptionStatus.APPROVED]: "已审核",
    [PrescriptionStatus.COMPLETED]: "已完成",
    [PrescriptionStatus.INVALID]: "已失效",
  };
  return statusMap[status] || "未知";
};

// 获取购药方式类型
const getPurchaseMethodType = (method: number) => {
  const methodMap: Record<number, string> = {
    [PurchaseMethod.PHARMACY]: "primary",
    [PurchaseMethod.ONLINE]: "success",
  };
  return methodMap[method] || "info";
};

// 获取购药方式文本
const getPurchaseMethodText = (method: number) => {
  const methodMap: Record<number, string> = {
    [PurchaseMethod.PHARMACY]: "药店购药",
    [PurchaseMethod.ONLINE]: "线上购药",
  };
  return methodMap[method] || "未知";
};

// 获取发药状态类型
const getDispensingStatusType = (status: number) => {
  const statusMap: Record<number, string> = {
    [DispensingStatus.PENDING]: "warning",
    [DispensingStatus.PROCESSING]: "primary",
    [DispensingStatus.COMPLETED]: "success",
    [DispensingStatus.CANCELLED]: "info",
  };
  return statusMap[status] || "info";
};

// 获取发药状态文本
const getDispensingStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    [DispensingStatus.PENDING]: "待支付",
    [DispensingStatus.PROCESSING]: "发药中",
    [DispensingStatus.COMPLETED]: "已发药",
    [DispensingStatus.CANCELLED]: "已取消",
  };
  return statusMap[status] || "未知";
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return "";
  return new Date(dateTime).toLocaleString("zh-CN");
};

// 返回上一页
const handleBack = () => {
  router.back();
};

// 加载订单详情
const loadOrderDetail = async () => {
  try {
    console.log("加载处方订单详情，ID:", orderId);
    const response = await OrderAPI.getPrescriptionOrderDetail(Number(orderId));

    if (response && response.data) {
      orderDetail.value = response.data;
      console.log("处方订单详情加载成功:", response.data);
    } else {
      console.error("API响应格式错误:", response);
      ElMessage.error("数据加载失败");
    }
  } catch (error) {
    console.error("加载处方订单详情失败:", error);
    ElMessage.error("数据加载失败，请检查网络连接");
  }
};

// 页面加载时获取数据
onMounted(() => {
  if (orderId) {
    loadOrderDetail();
  } else {
    ElMessage.error("订单ID不能为空");
    router.back();
  }
});

// 监听订单详情变化，更新页面标题
watch(
  orderDetail,
  (newDetail) => {
    if (newDetail.orderStatus !== undefined) {
      const statusText = getOrderStatusText(newDetail.orderStatus);
      document.title = `订单详情 - ${statusText}`;
    }
  },
  { deep: true }
);
</script>

<style scoped>
.prescription-detail {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-tag {
  margin-left: 10px;
}

.info-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  font-weight: 600;
  color: #333;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.info-item label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
  margin-right: 10px;
}

.info-item span {
  color: #333;
  flex: 1;
}

.amount {
  font-weight: 600;
  color: #e6a23c;
  font-size: 16px;
}

.coupon {
  font-weight: 600;
  color: #67c23a;
  font-size: 16px;
}

.actual-payment {
  font-weight: 600;
  color: #f56c6c;
  font-size: 16px;
}

.el-row {
  margin-bottom: 10px;
}

.el-col {
  margin-bottom: 10px;
}
</style>
